//
//  ClassicGameViewController.swift
//  2048Demo
//
//  Created by Windy on 2024/4/15.
//  Copyright © 2024 wpsd. All rights reserved.
//

import UIKit

class ClassicViewController: UIViewController {
    var cellRowCount = 4
    func saveDuration(_ duration: TimeInterval) {
        let defaults = UserDefaults.standard
        let bestTime = defaults.double(forKey: "bestTime")
        if bestTime == 0 || duration < bestTime {
            defaults.set(duration, forKey: "bestTime")
        }
    }
    var scoreView : UILabel?
    var gameTimer:Timer?
    var startTime: Date?
    override func viewDidLoad() {

        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        setupUI()
        // 创建背景图片视图并设置图片
           let backgroundImageView = UIImageView(frame: view.bounds)
           backgroundImageView.image = UIImage(named: "2")
           backgroundImageView.contentMode = .scaleToFill // 或者选择其他适合的模式
        
        // 将背景图片视图插入到视图层次的底部，确保它不会盖其他视图，如按钮等
           view.insertSubview(backgroundImageView, at: 0)
            }
    
    @objc func updateGameTime() {
            if let startTime = startTime {
                let currentTime = Date()
                let elapsedTime = Int(currentTime.timeIntervalSince(startTime))
                let hours = elapsedTime / 3600
                let minutes = (elapsedTime % 3600) / 60
                let seconds = elapsedTime % 60
                scoreView?.text = String(format: "TIME %02d:%02d:%02d", hours, minutes, seconds)
            }
        }
    func startGame() {
            startTime = Date()
            gameTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateGameTime), userInfo: nil, repeats: true)
        }
    func stopTimer() {
            gameTimer?.invalidate()
            gameTimer = nil
        }
    private func setupUI() {
        
       
        let boardWH = SCREEN_WIDTH - boardLeftMargin * 2
        let gameBoard = ClassicGameBoard(frame: CGRect(x: 0, y: 0, width: boardWH, height: boardWH),cellRowCount: cellRowCount)
            gameBoard.center = view.center
        var cellWH = (gameBoard.frame.width - margin * CGFloat(cellRowCount + 1)) / CGFloat(cellRowCount)
        var scoreW = cellWH * 3
        var scoreH = cellWH * 0.9
        gameTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(updateGameTime), userInfo: nil, repeats: true)
        gameBoard.resetGame()
        self.startGame()
        gameBoard.gameWin = { duration in
            self.stopTimer()
            self.saveDuration(duration)
            let bestTime = UserDefaults.standard.double(forKey: "bestTime")
            let durationFormatted = String(format: "%.2f seconds", duration)
            let bestTimeFormatted = String(format: "%.2f seconds", bestTime)
            
            // 自定义标题和消息
            let title = "Congratulations!"
            let message = "You've completed the game in \(durationFormatted). Best Time: \(bestTimeFormatted)"
            let attributedTitle = NSAttributedString(string: title, attributes: [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: .heavy),
                NSAttributedString.Key.foregroundColor: UIColor.darkGray
            ])
            let attributedMessage = NSAttributedString(string: message, attributes: [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15, weight: .regular),
                NSAttributedString.Key.foregroundColor: UIColor.gray
            ])

            let alertContr = UIAlertController(title: "Congratulations!", message: "You've completed the game in \(durationFormatted). Best Time: \(bestTimeFormatted)", preferredStyle: .alert)
            // 自定义按钮样式
            let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { _ in
                gameBoard.resetGame()
                self.startGame()  // 重新启动游戏
            })
            confirmAction.setValue(UIColor.blue, forKey: "titleTextColor")  // 修改按钮文字颜色

            alertContr.addAction(confirmAction)
            self.present(alertContr, animated: true, completion: nil)
        }

        gameBoard.gameOver = {
            self.stopTimer()
    let alertContr = UIAlertController(title: "Game Over", message:"Try Again", preferredStyle: .alert)
    let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { (alertAction) in
        gameBoard.resetGame()
        self.startGame()
        
    })
    alertContr.addAction(confirmAction)
    self.present(alertContr, animated: true, completion: nil)
}

        view.addSubview(gameBoard)
        
        cellWH = (gameBoard.frame.width - margin * CGFloat(4 + 1)) / CGFloat(4)
        scoreW = cellWH * 3
        scoreH = cellWH * 0.9
        scoreView = UILabel(frame: CGRect(x: 0, y: 0, width: scoreW, height: scoreH))
        scoreView?.center = CGPoint(x: SCREEN_WIDTH / 2, y: gameBoard.frame.minY - margin * 2 - scoreH / 2)
        scoreView?.font = UIFont.boldSystemFont(ofSize: 20)
        scoreView?.textAlignment = .center
        scoreView?.textColor = UIColor.white
        scoreView?.backgroundColor = UIColor.gray
        scoreView?.text = "TIME  00:00:00"
        scoreView?.layer.cornerRadius = 8
        scoreView?.clipsToBounds = true
        view.addSubview(scoreView!)
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 70))
            btn.setTitle("Undo", for: .normal)
        btn.setTitleColor(UIColor.black, for: .normal)
            btn.titleLabel?.font = UIFont(name: "Marker Felt", size: 36)
            btn.center = CGPoint(x: view.center.x-85, y: view.center.y + 180) // Adjust this to place it correctly
            btn.addTarget(gameBoard, action: #selector(ClassicGameBoard.undoLastMove), for: .touchUpInside)
            view.addSubview(btn)
        let btn1 = UIButton(frame: CGRect(x: 0, y: 0, width: 130, height: 70))
            btn1.setTitle("Restart", for: .normal)
        btn1.setTitleColor(UIColor.black, for: .normal)
            btn1.titleLabel?.font = UIFont(name: "Marker Felt", size: 36)
            btn1.center = CGPoint(x: view.center.x+85, y: view.center.y + 180) // Adjust this to place it correctly
            btn1.addTarget(gameBoard, action: #selector(ClassicGameBoard.resetGame), for: .touchUpInside)
            view.addSubview(btn1)
}}
